package com.qingcloud.adminbackend.controller;


import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.ImmutableMap;
import com.qingcloud.adminbackend.base.AjaxResult;
import com.qingcloud.adminbackend.constant.WamingConstant;
import com.qingcloud.adminbackend.entity.eid.*;
import com.qingcloud.adminbackend.enums.EidBatchStatusEnum;
import com.qingcloud.adminbackend.enums.ProductTypeEnum;
import com.qingcloud.adminbackend.exception.WmCommonException;
import com.qingcloud.adminbackend.service.ISysEquipmentidGenService;
import com.qingcloud.adminbackend.service.ISysEquipmentidListService;
import com.qingcloud.adminbackend.utils.AesUtil;
import com.qingcloud.adminbackend.utils.CookieUtil;
import com.qingcloud.adminbackend.entity.eid.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 设备编号生成 前端控制器
 * </p>
 *
 * @author wangjinnan
 * @since 2019-04-17
 */
@Api(value = "生成设备编号API", description = "生成设备编号API")
@RestController
@RequestMapping("/eidgen")
public class SysEquipmentidGenController {

    @Resource
    private ISysEquipmentidGenService sysEquipmentidGenService;

    @Resource
    private ISysEquipmentidListService sysEquipmentidListService;

    @ApiOperation(value = "生成设备编号", notes = "生成设备编号")
    @PostMapping("/create")
    public AjaxResult create(@Valid @RequestBody EidGenParam eidGenParam, HttpServletRequest request) {
        //如果是室外设备，编号要在10000内，并且要传城市编号
        if (eidGenParam.getProduct() != ProductTypeEnum.AIR_COMMON.code && eidGenParam.getProduct() != ProductTypeEnum.DECORATION.code) {
            if (eidGenParam.getBatchCount() < 1 || eidGenParam.getBatchCount() > 9999) {
                return new AjaxResult(WamingConstant.FAILURE, "生成数量要在1-9999之间", "");
            }
            if (eidGenParam.getDomainId() == null) {
                return new AjaxResult(WamingConstant.FAILURE, "城市不能为空", "");
            }
        } else {
            //不要城市ID
            eidGenParam.setDomainId(null);
        }
        //生成设备编号
        return new AjaxResult(WamingConstant.SUCCESS, "", sysEquipmentidGenService.create(eidGenParam, CookieUtil.getUserId(request)));
    }

    @ApiOperation(value = "分页查询设备编号批次", notes = "分页查询设备编号批次")
    @PostMapping(value = "/page")
    public AjaxResult<IPage<EidBatchPageDTO>> findStationGroupPage(@RequestBody EidBatchPageParam pageParam, HttpServletRequest request) {
        return new AjaxResult(WamingConstant.SUCCESS, "", sysEquipmentidGenService.searchPage(pageParam));
    }

    @ApiOperation(value = "作废编号批次", notes = "作废编号批次")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "批次ID", dataType = "string", paramType = "path", defaultValue = "1119158077770981376"),
    })
    @PostMapping(value = "/cancel/{id}")
    public AjaxResult cancel(@PathVariable("id") String id, HttpServletRequest request) {
        String userId = CookieUtil.getUserId(request);
        sysEquipmentidGenService.cancel(id, userId);
        return new AjaxResult(WamingConstant.SUCCESS, "", "");
    }

    @ApiOperation(value = "下载批次设备编号", notes = "下载批次设备编号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "批次ID", dataType = "string", paramType = "path", defaultValue = "1119158077770981376"),
    })
    @GetMapping(value = "/download/{id}")
    public void download(@PathVariable("id") String id, HttpServletResponse response) throws Exception {
        //查询批次状态
        SysEquipmentidGen sysEquipmentidGen = sysEquipmentidGenService.getById(id);
        if (sysEquipmentidGen.getBatchStatus() == EidBatchStatusEnum.CANCEL.code) {
            //批次已作废，不能下载
            throw new WmCommonException("批次已作废，不能下载");
        }
        //查询所有编号数据
        Collection<SysEquipmentidList> beanList = sysEquipmentidListService.listByMap(ImmutableMap.of("batch_id", id));
        List<SysEquipmentidExcel> idList = new ArrayList<>(beanList.size());
        beanList.forEach(it -> {
            ProductTypeEnum productTypeEnum = ProductTypeEnum.getByCode(it.getProduct());
            idList.add(new SysEquipmentidExcel(it.getEquipmentId(),
                    productTypeEnum.qrcodePrefix + AesUtil.encrypt(it.getEquipmentId())));
        });

        String fileName = "设备编号" + LocalDateTime.now().format(WamingConstant.NORMAL_FULL_FORMATTER) + ".xls";
        fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        ServletOutputStream out = response.getOutputStream();
        //创建xls格式的
        try (ExcelWriter writer = ExcelUtil.getWriter()) {
            //自定义标题别名
            writer.addHeaderAlias("equipmentId", "设备编号");
            writer.addHeaderAlias("qrcode", "二维码");
            // 一次性写出内容，使用默认样式，强制输出标题
            writer.write(idList, true);
            //out为OutputStream，需要写出到的目标流
            writer.flush(out);
        }
    }
}

